import fs from "fs"
import path from "path"
import { Buffer } from "buffer"

export default function viteFileUploadPlugin() {
    return {
        name: "vite-file-upload-plugin",
        configureServer(server) {
            server.middlewares.use("/upload", (req, res) => {
                if (req.method !== "POST") {
                    res.statusCode = 405
                    return res.end("Method Not Allowed")
                }

                let body = []
                req.on("data", (chunk) => {
                    body.push(chunk)
                }).on("end", () => {
                    try {
                        const data = Buffer.concat(body)
                        const filename = req.headers["x-file-name"] ? decodeURIComponent(req.headers["x-file-name"]) : `${Date.now()}`

                        // 改用不受HMR监控的目录
                        const uploadDir = path.join(process.cwd(), "static/uploads")
                        if (!fs.existsSync(uploadDir)) {
                            fs.mkdirSync(uploadDir, { recursive: true })
                        }

                        const filePath = path.join(uploadDir, filename)
                        fs.writeFileSync(filePath, data)

                        // 设置正确的响应头
                        res.setHeader("Content-Type", "application/json")
                        res.end(
                            JSON.stringify({
                                success: true,
                                filename: filename,
                                path: `/uploads/${filename}`, // 返回相对路径
                            })
                        )
                    } catch (error) {
                        console.error("Upload error:", error)
                        res.statusCode = 500
                        res.setHeader("Content-Type", "application/json")
                        res.end(
                            JSON.stringify({
                                success: false,
                                error: error.message,
                            })
                        )
                    }
                })
            })
        },
    }
}
